package com.globopt.global.algorithm;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;

/**
 * Simple class how to store the points (coordinates).
 * 
 * @author Richard Gasztany 2012.11.29.
 * 
 */
public class Point {
	private int nvars;
	private double[] coordinate;

	/**
	 * Init
	 * 
	 * @param nvars
	 */
	public Point(int nvars) {
		this.nvars = nvars;
		this.coordinate = new double[nvars];
	}

	/**
	 * Init with coordinates
	 * 
	 * @param coordinate
	 */
	public Point(double[] coordinate) {
		this.nvars = coordinate.length;
		this.coordinate = coordinate;
	}

	/**
	 * Returns a point with random generated coordinates within the specified
	 * interval.
	 * 
	 * @param lb
	 *            lower bound
	 * @param ub
	 *            upper bound
	 * @return Point
	 */
	public static Point random(double[] lb, double[] ub) {
		Random random = new Random();
		Point ret = new Point(lb.length);
		for (int i = 0; i < ret.nvars; i++) {
			ret.coordinate[i] = random.nextDouble() * (ub[i] - lb[i]) + lb[i];
		}
		return ret;
	}

	/**
	 * @return the nvars
	 */
	public int getNvars() {
		return nvars;
	}

	/**
	 * @return the coordinate
	 */
	public double getCoordinate(int i) {
		return coordinate[i];
	}

	/**
	 * To string method.
	 */
	public String toString() {
		String ret = "";
		for (int i = 0; i < nvars; i++) {
			// ret += "<td> " + formatter.format(coordinate[i]) + " </td>";
			ret += coordinate[i] + " ";
		}

		return ret;
	}

	/**
	 * To string method.
	 */
	public String toStringGlobalMin() {
		String ret = "";
		NumberFormat formatter = new DecimalFormat();
		formatter = new DecimalFormat("0.####E0");
		for (int i = 0; i < nvars; i++) {
			ret += "<td> " + coordinate[i] + " </td>";
		}

		return ret;
	}

	/**
	 * Calculates the distance between two points
	 * 
	 * @param p
	 * @return
	 */
	public double distance(Point p) {
		double ret = 0.0;
		for (int i = 0; i < nvars; i++) {
			ret += (p.coordinate[i] - this.coordinate[i]) * (p.coordinate[i] - this.coordinate[i]);
		}
		return Math.sqrt(ret);
	}
}
